import React, { Component } from 'react'
import { Card, Table, message, Button, Modal, Input, Upload, Icon } from "antd"
import './fileList.less'
import { reqFileList, reqFileDelete, reqFileReName, reqFileAdd } from '../../../../api'
import { to } from '../../../../utils'
import config from '../../../../config'
import memory from '../../../../utils/memory'
import copy from 'copy-to-clipboard'

const { Dragger } = Upload;

export default class FileList extends Component {
    state = {
        current: 1,
        size: 10,
        total: 0,
        dataSource: [],
        loading: false,
        newFilename: '',
        confirmLoading: false,
        uploadVisible: false,
        beforeUpload: false,
        fileList: [],
    }

    componentDidMount() {
        this.getFileList()
    }

    copyLink = (fileName) => {
        let link = config.public + '/user/' + memory.user.username + '/' + fileName
        if (copy(link)) {
            message.success('已复制到剪切板!')
        } else {
            message.error('复制失败,请手动复制!')
            Modal.info({
                title: '请手动复制!',
                content: (
                    <div>{link}</div>
                ),
                onOk() { },
            });
        }
    }

    reName = (filename) => {
        let index = filename.lastIndexOf(".")
        let preName = filename.substring(0, index)
        let suffix = filename.substring(index)
        if (!preName) [preName, suffix] = [suffix, preName]
        let that = this
        Modal.confirm({
            title: '重命名文件',
            content: (
                <div style={{ display: 'flex', alignItems: 'flex-end' }}>
                    <Input placeholder="请输入新文件名" defaultValue={preName} onChange={that.reNameInput} />
                    <span style={{ fontSize: 20 }}>{suffix}</span>
                </div>
            ),
            async onOk() {
                if (!that.state.newFilename) return message.error('请输入新的文件名!')
                let [err, res] = await to(reqFileReName(filename, that.state.newFilename + suffix))
                if (err) return
                if (res.code !== 0) return message.error(res.msg)
                message.success(res.msg)
                that.getFileList()
            },
        })
    }
    reNameInput = (e) => {
        this.setState({
            newFilename: e.target.value
        })
    }

    delete = (filename) => {
        let that = this
        Modal.confirm({
            title: `确定删除文件: ${filename} 吗?`,
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            async onOk() {
                that.setState({ loading: true })
                let [err, res] = await to(reqFileDelete(filename))
                that.setState({ loading: false })
                if (err) return console.log(err)
                if (res.code !== 0) {
                    message.error(res.msg)
                    return
                }
                message.success(res.msg)
                that.getFileList()
            }
        })

    }

    handleTableChange = (pagination) => {
        this.setState({
            current: pagination.current
        }, () => {
            this.getFileList()
        })
    }

    getFileList = async () => {
        this.setState({ loading: true })
        let [err, res] = await to(reqFileList(this.state.current, this.state.size))
        this.setState({ loading: false })
        if (err) return console.log(err)
        if (res.code !== 0) return message.error(res.msg)

        let fileList = res.body.fileList
        fileList.forEach(file => {
            file.kSize = (file.size / 1024).toFixed(1) + 'kb'
            file.modifyTime = file.mtime
        })
        this.setState({
            total: res.body.total,
            dataSource: fileList,
        })
    }

    handleUploadOk = async () => {
        if (!this.state.fileList.length) return message.error('请选择文件')
        let [err, res] = await to(reqFileAdd(this.state.fileList))
        if (err) return
        if (res.code !== 0) return message.error(res.msg)
        message.success(res.msg)
        this.setState({
            uploadVisible: false
        }, () => {
            this.getFileList()
        })
    }

    showUploadModal = () => {

        this.setState({
            uploadVisible: true
        })
    }

    handleUploadCancel = () => {
        this.setState({
            uploadVisible: false,
            fileList: []
        })
    }

    upLoadChange = (info) => {
        const { status } = info.file
        if (status === 'done') {
            const res = info.file.response
            if (res.code !== 0) return message.error(res.msg)
            let fileList = res.body
            this.setState({
                fileList: this.state.fileList.concat(fileList)
            })
        }
    }

    render() {
        const { dataSource, total, size, loading, uploadVisible, confirmLoading } = this.state
        const columns = [
            {
                title: '文件名',
                dataIndex: 'fileName',
                key: 'fileName',
            },
            {
                title: '大小',
                dataIndex: 'kSize',
                key: 'kSize',
            },
            {
                title: '修改时间',
                dataIndex: 'modifyTime',
                key: 'modifyTime',
            },
            {
                title: '操作',
                dataIndex: '',
                key: 'cz',
                render: (text, record) => (
                    <span>
                        <Button type="link" onClick={() => this.copyLink(record.fileName)}>复制链接</Button> |
                        <Button type="link" target="_blank" href={config.public + '/user/' + memory.user.username + '/' + record.fileName}>打开文件</Button> |
                        <Button type="link" onClick={() => this.reName(record.fileName)}>重命名</Button> |
                        <Button type="link" onClick={() => this.delete(record.fileName)}>删除</Button>
                    </span>
                ),
            },
        ]

        const props = {
            name: 'files',
            data: { token: memory.user.token },
            className: "file-list-uploader",
            action: config.host + '/file/upload',
            multiple: true,
            onChange: this.upLoadChange,

        }
        return (
            <Card title="文件列表" className="file-list" extra={<Button type="primary" onClick={this.showUploadModal}>上传文件</Button>}>
                <Table
                    dataSource={dataSource}
                    columns={columns}
                    rowKey='ino'
                    pagination={{ total, defaultPageSize: size }}
                    loading={loading}
                    onChange={this.handleTableChange}
                />

                <Modal
                    title="上传文件"
                    visible={uploadVisible}
                    onOk={this.handleUploadOk}
                    onCancel={this.handleUploadCancel}
                    confirmLoading={confirmLoading}
                    destroyOnClose={true}
                >
                    <Dragger {...props}>
                        <p className="ant-upload-drag-icon">
                            <Icon type="inbox" />
                        </p>
                        <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                    </Dragger>
                </Modal>
            </Card>
        )
    }
}
